-2

テンプレート引数と同じ型の要素のリストを使用する必要があるため、ベクトルを使用していますが、これを機能させる方法がわかりません

#include <iostream>
#include <cstdint>
#include <vector>

template <uint8_t VAL>
void foo()
{
    std::cout << "__" << std::endl;
};

template <>
void foo<3>()
{
    std::cout << "OK" << std::endl;
};

int main()
{
    std::vector<uint8_t> v = { 2, 4, 5, 2, 3, 55 };
    for (auto &k : v) {
        foo<k>();
    }
    return (0);
}

kコンパイラは基本的に ではないことについて不平を言いa constant expressionます。問題は、これを機能させるためにこれを変更する方法がわからないことです。反復するデータ構造が必要なので、ベクトルを保持する必要があります。単純化するためのテンプレートが必要です。見れば見るほど無限ループにハマってしまう。

4

5 に答える 5

1

整数値のコンパイル時の定数リストを反復処理する方法が本当に必要な場合:

#include <iostream>
#include <cstdint>

template <uint8_t VAL>
inline void foo()
{
    std::cout << "__" << std::endl;
}

template <>
void foo<3>()
{
    std::cout << "OK" << std::endl;
}

template <uint8_t... Values>
struct FooHelper {
  static void foo_all() {
  }
};

template <uint8_t First, uint8_t... Rest>
struct FooHelper<First, Rest...> {
  static void foo_all() {
    foo<First>();
    FooHelper<Rest...>::foo_all();
  }
};

template <uint8_t... Values>
void foo_all()
{
    FooHelper<Values...>::foo_all();
}

int main()
{
    foo_all<2, 4, 5, 2, 3, 55>();
}

正直なところ、そのユースケースはわかりませんが。

于 2013-07-21T16:39:44.127 に答える
0

コンパイラーは、コンパイル時に k の可能な値を推測する可能性がないため、これがどのように機能するかわかりませんか?

于 2013-07-21T06:36:49.270 に答える