[英]Why does std::apply fail with function template, but not with a lambda expression with explicit template parameter list?
[英]Why does the keyword `explicit` not apply to function parameters?
在某些情況下,可能不需要隱式類型轉換。
例如:
#include <string>
using namespace std;
void f(bool)
{}
void f(string)
{}
int main()
{
auto p = "hello";
f(p); // Oops!!! Call void f(bool); rather than void f(string);
}
如果C ++標准支持關鍵字explicit可用於限定函數參數,則代碼可能會更改如下:
#include <string>
using namespace std;
void f(explicit bool) // Illegal in current C++11 standard!
{}
void f(string)
{}
int main()
{
auto p = "hello";
f(p); // Call void f(string);
bool b = true;
f(b); // Call void f(bool);
f(8); // Error!
}
為什么C ++標准不支持這樣一個方便的功能?
#include <string>
#include <type_traits> // std::is_same
#include <utility> // std::enable_if
using namespace std;
template< class Value >
struct Explicit_
{
Value value;
operator Value() const { return value; }
template<
class Arg,
class Enabled = typename enable_if< is_same< Arg, Value >::value, void >::type
>
Explicit_( Arg const v ): value( v ) {}
};
void f( Explicit_<bool> ) // Valid in current C++11 standard!
{}
void f( string )
{}
int main()
{
auto p = "hello";
f(p); // Call void f(string);
bool b = true;
f(b); // Call void f(bool);
f(8); // Error!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.