次のコードがあります。
template <const char *p>
struct A{};
template <int i>
struct E{};
extern constexpr int i = 0;
constexpr float f = 0.f;
extern constexpr char c = 0;
int main(int argc, const char *argv[])
{
A<&c> b; //works
A<(const char *)(&i)> a; //Error: could not convert template argument ‘(const char*)(& i)’ to ‘const char*’
E<(int)f> e; //works
return 0;
}
なぜ行A<(const char *)(&i)> a;
が間違っているのですか?-std=c++0x を指定して g++-4.6.1 でコンパイルしました。
編集:チャールズが定数式では許可されていないことを示唆しreinterpret_cast
たように、上記のコードを次のように変更します。
struct Base{};
struct Derived : public Base {};
template <const Base *p>
struct A{};
extern constexpr Base base = {};
extern constexpr Derived derived = {};
A<&base> a; //works
A<(const Base*)&derived> b; //error: could not convert template argument ‘(const Base*)(& derived)’ to ‘const Base*’
したがって、許可されていないだけreinterpret_cast
ではありません。を使用A<static_cast<const base*>(&derived)
すると、同じエラーが発生します。
@BЈовићへ:
A<(const Base*)(0)> b; // error: could not convert template argument ‘0u’ to ‘const Base*’