我正在制作一个功能模板:
template <typename T>
void foo (T arg1) {}
Run Code Online (Sandbox Code Playgroud)
但我想确保T类型可以输入Foo,因此arg1
需要:
Foo * //This case T = Foo*
Run Code Online (Sandbox Code Playgroud)
要么
Any type X which implements `*` operator which returns a Foo/Foo&/Foo&&
Run Code Online (Sandbox Code Playgroud)
所以我需要这样的东西:
template <typename T>
void foo(T arg1, std::enable_if<std::is_same<typeid(*arg1), typeid(Foo)>::value> * = 0) {}
Run Code Online (Sandbox Code Playgroud)
但这不会编译和抱怨:
typecheck.cpp:6:54: error: use of parameter âarg1â outside function body
void foo(T arg1, std::enable_if<std::is_same<typeid(*arg1), typeid(Foo)>::value> * = 0) {}
^
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
您应该更喜欢使用is_convertible而不是is_same来捕获Foo的子类,模板参数列表中的enable_if而不是函数参数或返回类型也更容易阅读.
template <typename T, typename = typename std::enable_if<std::is_convertible<decltype( *std::declval<T>() ), Foo>::value>::type >
void foo(T arg1);
Run Code Online (Sandbox Code Playgroud)
c ++ 14中的垃圾少:
template <typename T, typename = std::enable_if_t<std::is_convertible<decltype( *std::declval<T>() ), Foo>::value> >
void foo(T arg1);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
540 次 |
最近记录: |