简体   繁体   English

如何拥有 TU 特定的 function 模板实例化?

[英]How to have TU-specific function template instantiation?

Let's say:比方说:

  • Some header h.hpp defines a template function f() using sizeof on its template parameter.一些 header h.hpp在其模板参数上使用sizeof定义了一个模板 function f()
  • Two different C++ source files, a.cpp and b.cpp , define their own structure having the same name S .两个不同的 C++ 源文件a.cppb.cpp定义了它们自己的同名结构S
  • Both a.cpp and b.cpp use f() with their own S . a.cppb.cpp都使用f()和它们自己的S

In other words:换句话说:

h.hpp : h.hpp :

template <typename T>
int f()
{
    return something + sizeof(T);
}

a.cpp : a.cpp

#include "h.hpp"

struct S {
    int a;
    int b;
};

int aFunc()
{
    return f<S>();
}

b.cpp : b.cpp :

#include "h.hpp"

struct S {
    int w;
    int x;
    int y;
    int z;
};

int bFunc()
{
    return f<S>();
}

Here, within the same program, both aFunc() and bFunc() return the same value .这里,在同一个程序中, aFunc()bFunc()都返回相同的值 This is because both structures are named S , and only one template function instantiation is kept.这是因为两个结构都命名为S ,并且只保留一个模板 function 实例化。

My working solutions so far are:到目前为止,我的工作解决方案是:

  1. Name the structures differently.以不同的方式命名结构。
  2. Make f() static .f() static
  3. Make f() part of an anonymous namespace.使f()成为匿名命名空间的一部分。
  4. Make both structures part of their own anonymous namespace.使这两个结构成为它们自己的匿名命名空间的一部分。

Can you think of anything else to avoid this issue which only manifests at run time?你能想出其他办法来避免这个只在运行时出现的问题吗?

I need to end this.我需要结束这一切。

Considering the comments of n.考虑到n 的评论。 1.8e9-where's-my-share m. 1.8e9-where's-my-share m. and VainMan : such a program is indeed ill-formed (ODR violation).VainMan :这样的程序确实格式错误(违反 ODR)。

Therefore, the only legal solutions are those (1 and 4):因此,唯一合法的解决方案是(1 和 4):

  • Name the structures differently.以不同的方式命名结构。
  • Make both structures part of their own anonymous namespace.使这两个结构成为它们自己的匿名命名空间的一部分。

I somehow stopped reading the One Definition Rule section at:我不知何故停止阅读一个定义规则部分:

There can be more than one definition in a program of each of the following: class type, enumeration type, inline function, inline variable (since C++17), templated entity (template or member of template, but not full template specialization), as long as all of the following is true:以下各项在程序中可以有多个定义:class 类型、枚举类型、内联 function、内联变量 (C++17 起)、模板化实体(模板或模板成员,但不是完全模板特化) , 只要满足以下所有条件:

  • each definition appears in a different translation unit每个定义出现在不同的翻译单元中

But there's another important condition:但是还有一个重要的条件:

  • each definition consists of the same sequence of tokens (typically, appears in the same header file)每个定义都包含相同的标记序列(通常出现在同一个 header 文件中)

This is obviously not my case.这显然不是我的情况。

The outcome of not satisfying any of those conditions is:不满足其中任何一个条件的结果是:

Otherwise, the program is ill-formed, no diagnostic required.否则,程序格式错误,不需要诊断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM