0

我在 test.h 标头中有一个像这样的简单函数

template <class Dst = std::string, class T>
Dst format(const T&);

template <class Dst, Class T>
Dst format(const T&) 
{
 return Dst();
}

在 test.cpp

#include "stdafx.h"
#include "test.h"
#include <iostream>
int main(int argc , char** argv)
{
    std::string f = format("");
    std::cout << f;
    return 0;
}

如果这个头文件被添加到 xcode 中的预编译头文件中

代码不再编译。

我收到“没有匹配的函数调用”错误。

如果我手动将默认参数添加到函数调用

format<std::string>();

然后它工作。

如果不是声明和定义,我只留下定义......它会编译。

4

2 回答 2

1

据我了解,如果标头包含模板,则无法对其进行预编译,因为编译器仅在使用来自其他来源的具体类型的这些函数时才从模板生成函数。没有具体类型 - 没有功能。

于 2017-01-20T14:09:03.370 回答
0

似乎如果我将默认参数放在 DEFINITION 而不是声明中,它似乎可以工作

template <class Dst , class T>
Dst format(const T&);

template <class Dst = std::string, Class T>
Dst format(const T&) 
{
 return Dst();
}
于 2017-01-20T16:17:31.520 回答