相关疑难解决方法(0)

在C++中使用'void'模板参数

采取以下最小例子:

using Type1 = std::function<void(void)>;

template <typename T>
using Type2 = std::function<void(T)>;

Type1 whyDoesThisWork;
Type2<void> andYetThisDoesNot;
Run Code Online (Sandbox Code Playgroud)

如果第二个类型别名,我得到错误"参数可能没有'void'类型".(我使用Xcode 4.5,Clang/c ++ 11/libc ++,OS X 10.7进行了测试.)

我发现这很奇怪:我本来期望Type1并且Type2<void>行为相同.这里发生了什么?有没有办法重写第二类型别名,所以我可以编写Type2<void>并获取std::function<void(void)>而不是错误?

编辑我应该补充一点,我想要的原因是允许以下内容:

template <typename ... T>
using Continuation = std::function<void(T...)>;

auto someFunc = []() -> void {
  printf("I'm returning void!\n");
};

Continuation<decltype(someFunc())> c;
Run Code Online (Sandbox Code Playgroud)

Continuation<decltype(someFunc())>成为Continuation<void>,我得到了错误.

c++ templates c++11 std-function

20
推荐指数
3
解决办法
3万
查看次数

std::conditional - 即使测试“void”,参数类型“void”也无效

在 Visual Studio 上编译如下:

\n
template<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}\n
Run Code Online (Sandbox Code Playgroud)\n

但不能在 Linux g++ 上编译。我得到的错误是

\n
error : invalid parameter type \xe2\x80\x98void\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n

我知道我不能在模板中使用 void,这就是我使用std::conditional_t和 的原因std::is_same_v

\n

我看不出什么是不正确的,有人可以告诉我吗?

\n

c++ templates class-template c++17 conditional-types

6
推荐指数
1
解决办法
631
查看次数