小编Pet*_*r H的帖子

与 std::lower_bound 相比,ranges::lower_bound 是否有不同的比较要求?

似乎在 C++20 中使用与 std::lower_bound() 正常工作的相同比较函子不适用于 std::ranges::lower_bound() 。以下代码无法使用 Visual Studio 16.10.2(和 /std::c++latest)或 gcc 11.1 进行编译。我可以通过使用投影而不是比较函子来解决这个问题,但这会增加迁移的工作量。

std::ranges::lower_bound() 中参数“comp”的要求是否与 std::lower_bound() 不同,如果是,如何?

#include <algorithm>
#include <vector>

struct A {
    double m_value;
};

struct MyComparison {
    bool operator()(const A& a, const double& b) {
        return a.m_value < b;
    }
};

void f() {
    std::vector<A> v = {A{1.0}, A{2.0}, A{3.0}};

    // comparison functor without ranges compiles as expected:
    auto x = std::lower_bound(v.cbegin(), v.cend(), 2.0, MyComparison());

    // projection with ranges compiles as expected:
    auto y = std::ranges::lower_bound(v, …
Run Code Online (Sandbox Code Playgroud)

c++ c++20

5
推荐指数
1
解决办法
78
查看次数

如何导出从 Visual Studio 中显式实例化的模板派生的类?

在我的 DLL 中,我有一个类模板和从该模板的实例化派生的第二个类。这两个类都应导出并可在其他 DLL 中使用。编译器是 Visual Studio 2013。我希望模板代码在一个翻译单元中被实例化,所以我使用显式实例化。

DLL1 中的代码分布如下。基类模板:

// In BaseTemplate.h:
#pragma once

template<typename T> 
class BaseTemplate
{
public:
    T foo(T t);
};

// declare explicit instantiation
extern template class BaseTemplate < int >;    

// In BaseTemplate.cpp:
#include "BaseTemplate.h"

// template method definition
template<class T>
T BaseTemplate<T>::foo(T t)
{
    return t;
}

// explicit instantiation and export
template class __declspec(dllexport) BaseTemplate < int >;    
Run Code Online (Sandbox Code Playgroud)

派生类:

// In Derived.h:
#pragma once
#include "BaseTemplate.h"

#ifdef DLL1_EXPORTS // this is predefined …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance templates visual-studio explicit-instantiation

4
推荐指数
1
解决办法
1989
查看次数

在类模板参数上调用模板方法

放入 .cpp 文件中的以下最小示例会导致 VisualStudio 2017(15.7.4,启用 /std:c++17)中出现编译器错误:

template <typename T>
class A
{
    void f(T& t)
    {
        t.g<2>();
    }
};

// B is a candidate for the template parameter T in A
struct B {
    template <int a>
    void g() {
        // nothing here
    }
};
Run Code Online (Sandbox Code Playgroud)

编译器错误引用 A::f() 的主体并显示:

error C2760: syntax error: unexpected token ')', expected 'expression' .
Run Code Online (Sandbox Code Playgroud)

请注意,A 和 B 都没有实际实例化。不声明 B 也会发生同样的错误。

但是,如果我切换声明 A 和 B 的顺序,则该示例将编译(并且可以实例化 A)。这很令人惊讶,因为我没有在代码中表达 A 和 B 之间的任何关系。另一个令人惊讶的事实是,将参数(例如 int)添加到 B::g() 的签名和 g() 的调用似乎也解决了错误(不改变声明的顺序)。

我的问题是:(1)为什么上面的代码会产生编译器错误?(2) …

c++ templates

2
推荐指数
1
解决办法
3046
查看次数