相关疑难解决方法(0)

std :: function的模板参数(签名)是不是它的类型?

鉴于以下代码,模糊性背后的原因是什么?我可以绕过它还是我必须保持(讨厌的)显式演员?

#include <functional>

using namespace std;

int a(const function<int ()>& f)
{
    return f();
}

int a(const function<int (int)>& f)
{
    return f(0);
}

int x() { return 22; }

int y(int) { return 44; }

int main()
{
    a(x);  // Call is ambiguous.
    a(y);  // Call is ambiguous.

    a((function<int ()>)x);    // Works.
    a((function<int (int)>)y); // Works.

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我a()function<int ()>参数注释掉函数并a(x)在我的main中调用,则编译正确失败,因为它们之间的类型不匹配xfunction<int (int)>唯一a()可用函数的参数.如果编译器在这种情况下失败,为什么在存在这两个a()函数时会有任何歧义?

我试过VS2010和g ++ v.4.5.两者都给我完全相同的歧义.

c++ c++11 std-function

39
推荐指数
2
解决办法
5696
查看次数

为什么我的C++编译器不能推导出boost函数的模板参数?

我定义了一个像这样的方法:

template <class ArgT>
void foo(ArgT arg, ::boost::function< void(ArgT) > func)
{
    func(arg);
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用 - 例如 - :

foo(2, [](int i) -> void { cout << i << endl; });
Run Code Online (Sandbox Code Playgroud)

为什么编译器不能推断出类型,因为它肯定是一个int

我得到'void foo(ArgT,boost::function<void(ArgT)>)' : could not deduce template argument for 'boost::function<void(ArgT)>' from 'anonymous-namespace'::<lambda0>'.

c++ templates

9
推荐指数
2
解决办法
1663
查看次数

可变参数函数中可变参数模板类的隐式转换

考虑以下代码

#include <functional>
template<class ResultType, class ... Args>
void Foo( std::function<ResultType(Args...)> ) {}

void Dummy(int) {}

int main()
{
     Foo<void, int> ( std::function<void(int)>( Dummy ) ); // OK, no deduction and no conversion
     Foo( std::function<void(int)>( Dummy ) ); // OK, template argument deduction
     Foo<void, int>( Dummy ); // Compile error
}
Run Code Online (Sandbox Code Playgroud)

在第三个中,我知道不能进行模板推导,这就是明确指定模板参数的原因。但是为什么没有从void (*)(int)to的显式转换std::function<void(int)>

我查找了答案,但这些是关于模棱两可的重载解决方案或模板推论,而不是相关主题。

std::function 的模板参数(签名)不是其类型的一部分吗?

使用 std::function 进行模板类型推导

使用 std::function 进行隐式转换

然后我尝试使用我自己的模板类而不是 std::function 进行测试。

// Variadic template class
template<class ... T>
class Bar
{ …
Run Code Online (Sandbox Code Playgroud)

c++ templates variadic-functions implicit-conversion variadic-templates

5
推荐指数
1
解决办法
169
查看次数