相关疑难解决方法(0)

什么是非弱化背景?

我最近接触过这个问题,答案可以概括为"这是一个非受限的背景".

具体来说,第一个说它是这样的东西,然后重定向到"细节"的标准,而第二个引用标准,这至少可以说是神秘的.

有人可以向凡人解释,比如我自己,什么是非受限的背景,什么时候发生,为什么会发生?

c++ templates template-argument-deduction argument-deduction

57
推荐指数
1
解决办法
4611
查看次数

为什么在将模板参数用作另一个模板的模板参数时,不能推导出模板参数?

这段代码有什么问题?

#include <map>

template<typename T>
struct TMap
{
    typedef std::map<T, T> Type;
};

template<typename T>
T test(typename TMap <T>::Type &tmap_) { return 0.0; }

int _tmain(int argc, _TCHAR* argv[])
{
    TMap<double>::Type tmap;
    tmap[1.1] = 5.2;
    double d = test(tmap); //Error: could not deduce template argument for T
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ parameters templates

51
推荐指数
1
解决办法
7500
查看次数

在非推导的上下文中解决模板参数的方法

请考虑以下代码:

#include <iostream>

template<class T>
struct outer {
    struct inner {};
};

template<class T>
std::ostream& operator<<(std::ostream & stream, 
                         typename outer<T>::inner const& value) {
    std::cout << "An outer::inner!";
    return stream;
}

int main() {
    outer<float>::inner foo;

    std::cout << foo << std::endl; // does not compile
}
Run Code Online (Sandbox Code Playgroud)

这不编译,因为typename outer<T>::innernondeduced背景(如解释在这里),这意味着模板参数的类型不能被编译器推导出(读这个答案的原因).在我看来,我有两个选项让它工作:

  1. 移动inner到外面outer并使其成为类模板.我更喜欢这个,因为对使用代码的影响较小.
  2. to_string在内部添加一个方法.

是否有任何其他解决方案(在使用代码中不会导致丑陋的语法)?

c++ templates template-argument-deduction

15
推荐指数
1
解决办法
1089
查看次数

为什么我需要在这里指定模板化函数的模板参数类型?

我有以下代码:

template <typename T>
void f1( T t )
{
    std::cout << "f1( " << t << " ) called." << endl;
}

template <typename T>
void f2( T t )
{
    std::cout << "f2( " << t << " ) called." << endl;
}

template <typename F, typename T>
void call( F && f, T t )
{
    f( t );
}

template <typename T>
void foo( T t )
{
    call( f1<T>, t ); // Why is <T> …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11

6
推荐指数
2
解决办法
821
查看次数