Ale*_*nov 1 c++ templates c++17
我想调用模板函数,即使std::enable_if_t没有解析为true. 它将允许我在其他上下文中重用我现有的模板之一。
最小的例子:
#include <iostream>
#include <type_traits>
template<typename T,
typename = typename std::enable_if<std::is_same<T, int>::value>::type>
auto foo(T t) {
std::cout << t << std::endl;
return t;
}
template<typename T>
auto bar(T t) {
foo(t);
}
int main() {
int i = 42;
foo(i); // ok already
// foo("42"); // shouldn't
bar("42"); // should
}
Run Code Online (Sandbox Code Playgroud)
I tried to solve it bydeclaring a bool in template argument list of foo and specify it when calling foo in bar, but I didn't quite manage to compile it without changing how foo is getting called in already existent code.
Is there any way to accomplish this? Maybe std::disjunction?
What you want doesn't make sense. Either a call to foo is valid or it isn't. It shouldn't matter who does it. enable_if is used to ward templates from cases where a particular parameter cannot work (or you have an alternate definition where it can). For example, if the definition is going to use a copy constructor, but the type doesn't have one. What you're using it for here doesn't fit that use case.
如果你真的需要做这样的事情,你可以将 的逻辑提取foo到一个单独的函数中,foo和bar调用。