小编Mig*_*uel的帖子

C ++模板运算符+内部类中的重载

如何为类模板的内部类重载 operator+?我已经搜索了几个小时,但找不到答案。这是一个不起作用的最小示例:

#include <iostream>
using namespace std;

template <class T>
struct A
{
    struct B
    {
        T m_t;
        B(T t) : m_t(t) {}
    };


};

template <class T>
typename A<T>::B operator+(typename A<T>::B lhs, int n)
{
    lhs.m_t += n;
    return lhs;
}

int main(int argc, char **argv) 
{

    A<float> a;
    A<float>::B b(17.2);
    auto c = b + 5;
    cout << c.m_t << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我这样编译,我得到 error: no match for ‘operator+’ (operand types are ‘A<float>::B’ and ‘int’)

我找到了operator+(A<T>::B, …

c++ templates operator-overloading

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

C++:制作一个没有包含的单个文件

这可能听起来像一个非常奇怪的问题,但我确实需要这个:我有一堆c ++头文件(来自一些只有头的库)和一个cpp文件.我想要做的是生成一个没有包含任何内容的单个cpp文件.

为什么?对于一个比赛,其中编译器没有我正在使用的库,以及一个只能提交一个cpp文件的库.

理想情况下,这个"脚本"会创建一个仅使用实际需要的文件,而不仅仅是复制和粘贴所有"#includes".

我确信在代码中添加"#include"时预处理器会生成一些文件.那么,我怎样才能看到这些中间文件(可能很长)?

c++ include single-file c-preprocessor

3
推荐指数
1
解决办法
663
查看次数

在C++中n = {0,1,...,n-1}

自然数n的形式定义(在集合论中)如下:

  • 0是空集
  • 1 = {0}
  • n = {0,1,...,n-1}

我认为这会使一些C++代码更简单,如果我被允许这样做:

for (int n : 10)
    cout << n << endl;
Run Code Online (Sandbox Code Playgroud)

它打印的数字从0到9.

所以我尝试执行以下操作,但不编译:

#include <iostream>
#include <boost/iterator/counting_iterator.hpp>


    boost::counting_iterator<int> begin(int t)
    {
        return boost::counting_iterator<int>(0);
    }

    boost::counting_iterator<int> end(int t)
    {
        return boost::counting_iterator<int>(t);
    }



int main() 
{
    for (int t : 10)
        std::cout << t << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有关如何实现这一目标的任何建议?我用clang ++得到以下错误:

main.cpp:22:20: error: invalid range expression of type 'int'; no viable 'begin' function available
        for (int t : 10)
                ^ ~~
Run Code Online (Sandbox Code Playgroud)

但我想我应该被允许这样做!:)

编辑:我知道如果我在for循环中添加"range"(或其他一些单词)这个词,我可以"伪造"它,但我想知道是否可以不使用它.

c++ set-theory c++14

0
推荐指数
1
解决办法
1103
查看次数