10

これらのテンプレートエイリアスがあるとしましょう。

enum class enabler {};

template <typename T>
using EnableIf = typename std::enable_if<T::value, enabler>::type;
template <typename T>
using DisableIf = typename std::enable_if<!T::value, enabler>::type;

GCCで次のことができます。

#include <iostream>

template <typename T, EnableIf<std::is_polymorphic<T>> = {}>
void f(T) { std::cout << "is polymorphic\n"; }

template <typename T, DisableIf<std::is_polymorphic<T>> = {}>
void f(T) { std::cout << "is not polymorphic\n"; }

struct foo { virtual void g() {} };

int main() {
    f(foo {});
    f(int {});
}

それは印刷します:

多形である多形
ではない

これは私の期待に一致します。

clangを使用すると、そのコードはコンパイルされません。次のエラーメッセージが表示されます。

test.cpp:11:58: error: expected expression
template <typename T, EnableIf<std::is_polymorphic<T>> = {}>
                                                         ^
test.cpp:14:59: error: expected expression
template <typename T, DisableIf<std::is_polymorphic<T>> = {}>
                                                          ^
test.cpp:20:3: error: no matching function for call to 'f'
  f(foo {});
  ^
test.cpp:12:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is polymorphic\n"; }
     ^
test.cpp:15:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is not polymorphic\n"; }
     ^
test.cpp:21:3: error: no matching function for call to 'f'
  f(int {});
  ^
test.cpp:12:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is polymorphic\n"; }
     ^
test.cpp:15:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is not polymorphic\n"; }
     ^
4 errors generated.

コンパイルする必要がありますか?2つのコンパイラのどちらに障害がありますか?

4

1 に答える 1

7

何よりもまず、説明をしてくれたoftcの#llvmIRCチャネルの@RichardSmithに感謝します。
残念ながら、これは正当なC ++ではないため、Clangは正しいです。{}これは式ではなくbraced-init-listであるため、非型テンプレートパラメーターの初期化子で必要とされる定数式にはなりません。

§14.3.2 [temp.arg.non-type] p1

非型、非テンプレートのテンプレートパラメータのテンプレート引数は、次のいずれかである必要があります。

  • 整数型または列挙型の非型テンプレートパラメーターの場合、テンプレートパラメーターの型の変換された定数式(5.19)。また
  • [...]

1つの解決策は、のダミー値ですenabler

于 2012-04-16T20:54:15.630 に答える