c ++标题多次使用

时间:2013-09-25 02:09:28

标签: c++ templates

我有一个模板类A,其类型参数为T。 我的程序为类型参数生成多个版本 - T_1,..,T_N。此外,对于每种类型T_i,具有A<T_i>的代码将编译到库lib_i中。最后,对于每个lib_i,我从A<T_i>调用一个函数。但是,我总是得到与T_1相对应的结果。可能是什么问题?

以下是更多细节。

文件结构:

  • A.hpp
  • LIB1
    • main1.cpp
    • T1.hpp
    • lib1.so
  • LIB2
    • main2.cpp
    • T2.hpp
    • lib2.so
  • libN
    • mainN.cpp
    • TN.hpp
    • libN.so

示例:

A.hpp:

template <class T>
class A
{
    void foo()
    {
        std::cout << T::K << std::endl;
    }
};

T1.hpp:

class T1
{
    enum { K = 1 };
};

T2.hpp:

class T2
{
    enum { K = 2 };
};

main1.cpp和main2.cpp都调用A :: foo()。 但输出始终为1。

更新

main1.cpp:

#include "../A.hpp"
#include "T1.hpp"

int main(int argc, char **argv)
{
    A<T1> a;
    a.foo();
    return 0;
}

main2.cpp:

#include "../A.hpp"
#include "T2.hpp"

int main(int argc, char **argv)
{
    A<T2> a;
    a.foo();
    return 0;
}

UPDATE2:

这在mac os x上发生。

g ++ -v

使用内置规格。 COLLECT_GCC =克++ COLLECT_LTO_WRAPPER = /选择/本地/ libexec目录/ GCC / x86_64的 - 苹果darwin11 / 4.7.2 / LTO-包装 目标:x86_64-apple-darwin11 配置为:../ gcc-4.7.2/configure --prefix = / opt / local --build = x86_64-apple-darwin11 --enable-languages = c,c ++,objc,obj-c ++,lto,fortran, java --libdir = / opt / local / lib / gcc47 --includedir = / opt / local / include / gcc47 --infodir = / opt / local / share / info --mandir = / opt / local / share / man - -datarootdir = / opt / local / share / gcc-4.7 --with-libiconv-prefix = / opt / local --with-local-prefix = / opt / local --with-system-zlib --disable-nls - -program-suffix = -mp-4.7 --with-gxx-include-dir = / opt / local / include / gcc47 / c ++ / --with-gmp = / opt / local --with-mpfr = / opt / local --with-mpc = / opt / local --with-ppl = / opt / local --with-cloog = / opt / local --enable-cloog-backend = isl --disable-cloog-version-check - enable-stage1-checking --enable -lto --enable-libstdcxx-time --with-as = / opt / local / bin / as --with-ld = / opt / local / bin / ld --with-ar = / opt / local / bin / ar --with-bugurl = https://trac.macports.org/newticket --disable-ppl-version-check --with-pkgversion ='MacPorts gcc47 4.7.2_2 + universal' 线程模型:posix gcc版本4.7.2(MacPorts gcc47 4.7.2_2 +通用)

但是它在linux上运行正常。

g ++ -v

使用内置规格。 COLLECT_GCC =克++ COLLECT_LTO_WRAPPER =的/ usr / gcc_4_7 /的libexec / GCC / x86_64的-Linux的GNU / 4.7.0 / LTO-包装 目标:x86_64-linux-gnu 配置为:../ gcc-4.7.0/configure --build = x86_64-linux-gnu --prefix = / usr / gcc_4_7 --with-gmp = / usr / gcc_4_7 --with-mpfr = / usr / gcc_4_7 --with-mpc = / usr / gcc_4_7 --enable-checking = release --enable-languages = c,c ++,fortran --disable-multilib --program-suffix = -4.7 线程模型:posix gcc版本4.7.0(GCC)

UPDATE3:

我的解释是误导性的,因为我实际上是在创建具有相同名称的文件(lib1 / T.hpp,lib2 / T.hpp,..)。类型T_i的名称也相同。通过在相应目录中包含T.hpp来选择正确的一个。 为T_i使用不同的名称(不适用于T_i.hpp)解决了这个问题。但是,我仍然想知道当类型名称相同时出了什么问题。

1 个答案:

答案 0 :(得分:1)

我尝试了你的代码,它运行正常。 A<T2> a; a.foo()将输出2。

由于T.hpp和main.cpp具有相同的名称,我担心错误的代码会被链接。

您可能希望使用不同的文件名。 :)