最小的可复制示例
#include <unordered_map>
#include <string>
template<class T, bool did_work>
class Test {
Test(T input) : field(input), success(did_work) {}
T field;
bool success;
};
template<typename A>
void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {}
int main() {}
输出:
$ g++ -std=c++17 -ggdb -g3 -Wall test.cpp && ./a.out
test.cpp:12:51: error: type/value mismatch at argument 2 in template parameter list for ‘template<class T, bool did_work> class Test’
12 | void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {}
| ^~~~
test.cpp:12:51: note: expected a constant of type ‘bool’, got ‘bool’
test.cpp:12:55: error: template argument 2 is invalid
12 | void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {}
| ^~
test.cpp:12:55: error: template argument 5 is invalid
我需要能够在传递unordered_map<std::string, Test<A, true>>
以及unordered_map<std::string, Test<A, false>>
。有没有一种方法可以在函数定义中执行此操作而不更改类Test
定义?
Withtemplate<class T, bool did_work>
did_work
是非类型模板参数。这意味着它要传递一个值,而不是将类型传递给它。由于它需要一个值,因此您可以点Test
赞Test<A, true>
或Test<A, false>
而不是Test<A, bool>
。
对于您的函数,您只需添加一个非类型模板参数即可
template<typename A, bool did_work>
void func(std::unordered_map<std::string, Test<A, did_work>> input1, A input2) {}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句