我以前曾问过this这个问题,涉及将auto与可变参数模板一起使用,该模板生成元组以及对其进行迭代的正确方法。用户metalfox为我提供了this解决方案。
我尝试了他们的解决方案,这就是我的完整代码,包括我原来在其中省略的名称空间。
计算小时
#include <algorithm>
#include <iostream>
#include <tuple>
#include <utility>
namespace math {
template<class... T>
class expression_t {
public:
std::tuple<T...> rhs;
std::size_t size = sizeof...(T);
//expression_t(const T&... args) : rhs{ args... } {}
template <class... Args>
expression_t(Args&& ...args) : rhs(std::forward<Args>(args)...) {}
std::tuple<T...> operator()() const {
return rhs;
}
};
template<typename T>
void Print(std::ostream& os, T x) {
os << x;
}
template<>
void Print<char>(std::ostream& os, char x) {
if (x == '+' || x == '-' || x == '*' || x == '/' || x == '%')
os << ' ' << x << ' ';
}
template<class... Args>
expression_t<Args...> expression(Args... args) {
expression_t<Args...> expr(args...);
return expr;
}
template<class... Args>
std::ostream& operator<<(std::ostream& os, const expression_t<Args...>& expr) {
auto Fn = [&os](auto... x) {
(Print(os, x), ...);
};
std::apply(Fn, expr.rhs);
os << '\n';
return os;
}
}
main.cpp
#include "calc.h"
using namespace math;
int main() {
double x = 0;
auto expr = expression(4, x, '^', 2, '+', 2, x);
auto t = expr();
std::cout << std::get<2>(t);
std::cout << expr;
return 0;
}
在构建过程中它会生成此链接器错误:
1>------ Build started: Project: ChemLab, Configuration: Debug x64 ------
1>main.obj : error LNK2005: "void __cdecl math::Print<char>(class std::basic_ostream<char,struct std::char_traits<char> > &,char)" (??$Print@D@math@@YAXAEAV?$basic_ostream@DU?$char_traits@D@std@@@std@@D@Z) already defined in calc.obj
1>C:\***\test.exe : fatal error LNK1169: one or more multiply defined symbols found
1>Done building project "ChemLab.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
声明并定义这些打印函数以防止在单个翻译单元中多次定义它们的正确方法是什么?
答案 0 :(得分:2)
函数模板专门化(例如您的示例中的Print<char>
)是常规函数,而不是模板。必须只定义一次,或者使用inline
关键字定义。