Wad*_*Wad 6 c++ templates class-template c++17 conditional-types
在 Visual Studio 上编译如下:
\ntemplate<typename ArgType, typename ReturnType>\nstruct Test\n{\n using FunctionPointerType = std::conditional_t<\n std::is_same_v<ArgType, void>\n , ReturnType(*)()\n , ReturnType(*)(ArgType)\n >;\n FunctionPointerType Func;\n};\n\nint main()\n{\n Test<void, char> tt;\n}\nRun Code Online (Sandbox Code Playgroud)\n但不能在 Linux g++ 上编译。我得到的错误是
\nerror : invalid parameter type \xe2\x80\x98void\xe2\x80\x99\nRun Code Online (Sandbox Code Playgroud)\n我知道我不能在模板中使用 void,这就是我使用std::conditional_t和 的原因std::is_same_v。
我看不出什么是不正确的,有人可以告诉我吗?
\n在和专业化中std::conditional_t<B, T, F>都应该具有有效的类型和。在您的情况下,由于推断出无效类型,因此不能在此处使用。truefalseTFFchar(*)(void)std::conditional
我建议使用辅助特征function_ptr_t作为替代
#include <type_traits>
template<typename RetType, typename... Args> struct function_ptr final {
using type = RetType(*)(Args...);
};
template <typename RetType> struct function_ptr<RetType, void> final {
using type = RetType(*)();
};
// alias helper
template<typename RetType, typename... Args>
using function_ptr_t = typename function_ptr<RetType, Args...>::type;
template<typename RetType, typename... Args>
struct Test
{
function_ptr_t<RetType, Args...> Func;
};
Run Code Online (Sandbox Code Playgroud)
请注意,我已经交换了类 template 中的模板参数Test,并使第二个模板参数成为变量,以便将Test<char>生成类型为 的成员函数指针char(*)()。
这意味着以下内容将起作用:
Test<char> tt1;
static_assert(std::is_same_v<char(*)(), decltype(tt1.Func)>, " are not same!");
Test<char, void> tt2;
static_assert(std::is_same_v<char(*)(), decltype(tt2.Func)>, " are not same!");
Test<void, double> tt3;
static_assert(std::is_same_v<void(*)(double), decltype(tt3.Func)>, " are not same!");
Run Code Online (Sandbox Code Playgroud)
如果不是,您想要将可变参数模板参数替换为普通参数。
| 归档时间: |
|
| 查看次数: |
631 次 |
| 最近记录: |