【发布时间】:2019-07-03 13:33:39
【问题描述】:
根据我是使用 -O3 编译还是未优化编译,编译器不会选择相同的函数模板实例化。使用 gcc (Debian 8.3.0-6) 8.3.0。
由于疏忽,我在函数模板声明中有一个默认实现:
#pragma once
#include <iostream>
template <int>
void func() { std::cerr << "default impl\n"; } // normally no impl here
以及他们的专长:
#include "func.h"
template <>
void func<1>()
{
std::cerr << "special 1\n";
}
template <>
void func<2>()
{
std::cerr << "special 2\n";
}
还有主要功能。
#include "func.h"
int main(void)
{
func<1>();
func<2>();
return 0;
}
编译和运行g++ -Wall func.cpp main.cpp -o main && ./main 给出:
special 1
special 2
使用优化 g++ -O3 -Wall func.cpp main.cpp -o main && ./main 给出:
default impl
default impl
这是预期的吗?代码是否触发了我不知道的意外行为?
感谢制作Wandbox 的cmets 的@NathanOliver。编译有或没有优化显示不同的输出。
【问题讨论】:
-
专业化定义在哪里?
-
您能否将您的代码 sn-ps 替换为 minimal reproducible example,作为可以复制、粘贴和编译而无需将它们拼接在一起的单段代码?
-
@BiagioFesta 这可能是因为您的示例不等效,您的示例中没有输出,因此编译器优化了所有内容
-
@eerorika 专业化在 func.cpp 中。
-
@StoryTeller 这是有趣的信息,因此它应该是问题的一部分。